package Servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import ServerDB.Folder; 
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import ServerDB.User;

/**
 * Servlet:: Get all the folder of user
 * @author Guy & Liel
 *
 */
public class UserFoldersServlet  extends HttpServlet
{

	//NOTE: we using two session, the first is of Hibernate and the second is for session of email
	private static final long serialVersionUID = 1L;
	/**
	 * Request an user name and send all his folders;
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		User user = null;
		// ...

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		out.println("<HTML>");
		out.println("<HEAD>");
		System.out.println("Check sending password");
		String userName=request.getSession().getAttribute("Login").toString();
		System.out.println("My user name is : "+userName);
		File file=new File("C:\\ourDropBox\\hibernate.cfg.xml");
		SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
		org.hibernate.classic.Session sessionHibernate=sessionFactory.openSession();
		String strQuery="FROM User e WHERE e.userName=:userNameQry";
		Query query=sessionHibernate.createQuery(strQuery);
		query.setParameter("userNameQry", userName);
		System.out.println("After SQL line");
		@SuppressWarnings("unchecked")
		List<User> listUsers=query.list();
		Iterator<User> itUser=listUsers.iterator();

		if(itUser.hasNext())//Response The user name is in DataBase
		{

			System.out.println("my user is");
			user=itUser.next();
			Set<Folder> setFolders=user.getFolders();
			HttpSession httpSession=request.getSession(true);
			httpSession.setAttribute("Folders", setFolders);
			out.println("<meta HTTP-EQUIV='REFRESH' content='0; url=myFolder.jsp'>");
			out.println("</HEAD>");
			out.println("<BODY>");
			out.println("</BODY>");
			out.println("</HTML>");
			out.close();

		}
	}	
}

